/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.extension.security.internal.analyzer;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.xwiki.extension.CoreExtension;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.index.internal.ExtensionIndexStore;
import org.xwiki.extension.index.security.ExtensionSecurityAnalysisResult;
import org.xwiki.extension.index.security.SecurityVulnerabilityDescriptor;
import org.xwiki.extension.index.security.review.ReviewsMap;
import org.xwiki.extension.repository.CoreExtensionRepository;
import org.xwiki.extension.repository.internal.core.DefaultCoreExtension;
import org.xwiki.extension.repository.internal.core.DefaultCoreExtensionRepository;
import org.xwiki.extension.version.internal.DefaultVersion;
import org.xwiki.test.LogLevel;
import org.xwiki.test.junit5.LogCaptureExtension;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.test.junit5.mockito.MockComponent;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Test of {@link VulnerabilityIndexer}.
 *
 * @version $Id$
 */
@ComponentTest
class VulnerabilityIndexerTest
{
    @InjectMockComponents
    private VulnerabilityIndexer indexer;

    @MockComponent
    private ExtensionIndexStore extensionIndexStore;

    @MockComponent
    private CoreExtensionRepository coreExtensionRepository;

    @RegisterExtension
    private LogCaptureExtension logCapture = new LogCaptureExtension(LogLevel.WARN);

    @Test
    void update() throws Exception
    {
        ExtensionId extensionId = new ExtensionId("org.xwiki:ext", "12.10");
        DefaultCoreExtension extension =
            new DefaultCoreExtension(mock(DefaultCoreExtensionRepository.class), new URL("file:///path/ext.jar"),
                extensionId, "exttype");
        ExtensionSecurityAnalysisResult inputAnalysis = new ExtensionSecurityAnalysisResult()
            .setResults(List.of());
        boolean update = this.indexer.update(extension, inputAnalysis, new ReviewsMap());

        assertFalse(update);

        verify(this.extensionIndexStore).update(extensionId, new ExtensionSecurityAnalysisResult()
            .setCoreExtension(true)
            .setResults(List.of()));
    }

    @Test
    void updateWithVulnerabilities() throws Exception
    {
        CoreExtension environmentCoreExtension = mock(CoreExtension.class);
        when(environmentCoreExtension.getURL()).thenReturn(new URL("file:/path"));
        when(this.coreExtensionRepository.getEnvironmentExtension()).thenReturn(environmentCoreExtension);
        
        ExtensionId extensionId = new ExtensionId("org.xwiki:ext", "12.10");
        DefaultCoreExtension extension =
            new DefaultCoreExtension(mock(DefaultCoreExtensionRepository.class), new URL("file:///path/ext.jar"),
                extensionId, "exttype");
        SecurityVulnerabilityDescriptor securityVulnerabilityDescriptor = new SecurityVulnerabilityDescriptor()
            .setScore(1.3)
            .setId("org.xwiki.ext/12.10")
            .setURL("https://ext.dev/path")
            .setFixVersion(new DefaultVersion("15.2"));
        ExtensionSecurityAnalysisResult inputAnalysis = new ExtensionSecurityAnalysisResult()
            .setResults(List.of(securityVulnerabilityDescriptor));

        boolean update = this.indexer.update(extension, inputAnalysis, new ReviewsMap());

        assertTrue(update);

        verify(this.extensionIndexStore).update(extensionId, new ExtensionSecurityAnalysisResult()
            .setAdvice("extension.security.analysis.advice.upgradeXWiki")
            .setCoreExtension(true)
            .setResults(List.of(securityVulnerabilityDescriptor)));
    }

    @Test
    void updateIsNotServlet() throws Exception
    {
        ExtensionId extensionId = new ExtensionId("org.xwiki:ext", "12.10");

        DefaultCoreExtension extension =
            new DefaultCoreExtension(mock(DefaultCoreExtensionRepository.class), getWebjarExtensionURL(),
                extensionId, "exttype");
        ExtensionSecurityAnalysisResult inputAnalysis = new ExtensionSecurityAnalysisResult()
            .setResults(List.of());
        boolean update = this.indexer.update(extension, inputAnalysis, new ReviewsMap());

        assertFalse(update);

        verify(this.extensionIndexStore).update(extensionId, new ExtensionSecurityAnalysisResult()
            .setCoreExtension(true)
            .setResults(List.of()));
    }

    private static URL getWebjarExtensionURL() throws MalformedURLException
    {
        Path root = Path.of(".").toAbsolutePath();
        return root.resolve(Path.of("webapps", "ext.jar")).toUri().toURL();
    }
}
